package com.studyroom.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.studyroom.annotation.PassToken;
import com.studyroom.util.JwtTokenUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j;
import org.springframework.expression.ExpressionException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.nio.channels.InterruptedByTimeoutException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wuhongbin
 * @version 1.0.0
 * @ClassName JwtTokenInterceptor.java
 * @Description token拦截器
 * @createTime 2021年11月01日 18:40:00
 */
@Log4j
public class JwtTokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        String token = request.getHeader("authorization");
        log.info("当前token为 :{"+ token + "}");
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        // 拥有passtoken方法的注解跳过验证
        if (method.isAnnotationPresent(PassToken.class)){
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }else{
            if (token == null){
                throw new ExpressionException("您当前未登录,请先登录!");
            }else{
                Claims claims = JwtTokenUtils.getClaimsFromToken(token);
            }
            return true;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
